#!/bin/bash
json_file="./mit_api5virtualnodes.json"
product() {
  echo 'ASCG'
}

boardcfg() {
   echo 1
}

tag2nid() {
    echo "0x151$(($1 - 1))"
}

json_container_nums() {
    python3 - <<END
import json

with open('$json_file', 'r') as file:
    data = json.load(file)
ascg_data = data.get('$(product)', {})
one_data = ascg_data.get('$(boardcfg)', {})

if one_data:
    print(len(one_data))
else:
    print(0)
END
}

noc=$(json_container_nums)

if [[ ! "${noc}" =~ ^[0-9]+$ ]]; then
    echo "Error: container_nums is not a valid integer."
    exit 1
else
    echo "There are ${noc} containers"
fi

declare -a info_array

for ((i=1; i<=noc; i++)); do
    info=$(python3 - <<END
import json

with open('$json_file', 'r') as file:
    data = json.load(file)
ascg_data = data.get('$(product)', {})
one_data = ascg_data.get('$(boardcfg)', {}).get(str($i), {})

if one_data:
    container_type = one_data.get('containerType', '')
    instance_number = one_data.get('instanceNumber', '')
    nrt_core_affinity_list = one_data.get('rtCoreAffinityList', '')
    huge_page_number = one_data.get('hugePageDataPlane', [{}])[0].get('HugePageNumber', '')

    print(f"{container_type} {instance_number} {nrt_core_affinity_list} {huge_page_number}")
else:
    print("Tag not found.")
END
)
    info_array[$i]=$info
done

container_info() {
    echo "container  $(tag2nid $1) ${info_array[$1]}"
}

container_infos() {
   echo "READ json from ${json_file}"
   echo "Product $(product) bdcfg $(boardcfg)"
   echo "container_nums ${noc}"   
   for ((i=1; i<=noc; i++)); do
      container_info $i
   done
}

container_start() {
    local nid="$(tag2nid $1)"
    echo "Container----------------$nid starting"
	IFS=' ' read -r type inst rtc hpdp <<< "${info_array[$1]}"
    cmd="python3 SupervisorS.py -p 15003 -t $type -i $inst -v $1 -n "0x1011" --pv 0xc3 --fid 1 --bucn 0 --ncw 20 --nrtc 0,1,2,3 --rtc ${rtc} --hpdp ${hpdp} -o start_uplane_api5"
    #cd /opt/hwmt/python/hwapi && export PYTHONPATH=./
	echo $cmd
}

container_stop() {
    local nid="$(tag2nid $1)"
    echo "Container----------------$nid stopping"
}

container_stop_all()
{
    echo "There are ${noc} containers"
    for ((t=1; t<=${noc}; t++)); do
        container_stop $t 
    done
}

container_reset()
{
    echo "RESET for container $1"
    container_stop $1
    container_start $1
}

container_reset_all()
{
    echo "There are ${noc} containers"
    for ((t=1; t<=${noc}; t++)); do
        container_reset $t &
    done
	wait
}

